package com.pansoft.kline.fragment;


import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import com.efounder.constant.EnvironmentVariable;
import com.github.mikephil.charting.jobs.MoveViewJob;
import com.pansoft.kline.util.KLineUtil;
import com.pansoft.klinelib.chart.TimeLineView;
import com.pansoft.klinelib.model.ChartLoadMoreEvent;
import com.pansoft.klinelib.model.ClickPositionEvent;
import com.pansoft.klinelib.model.HisData;
import com.pansoft.openplanet.R;
import com.utilcode.util.TimeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import static com.pansoft.klinelib.chart.KLineView.CHART_MAIN_INDEX;
import static com.pansoft.klinelib.chart.KLineView.CHART_SUB_INDEX;
import static com.pansoft.klinelib.util.KLineConstant.K_LINE_TYPE_MINUTE;
import static com.pansoft.openplanet.constant.MarketConstant.K_LINE_API_VERSION;


/**
 * 分时图
 * @author will
 */
public class TimeLineChartFragment extends Fragment {


    private TimeLineView mTimeLineView;
    private ProgressBar progressBar;
    private String type, marketId = "";
    private View v;

    private List<HisData> hisDataList = new ArrayList<>();
    private String beforeTime = "";

    public static final String TAG = "TimeLineChartFragment";

    public TimeLineChartFragment() {
        // Required empty public constructor
    }

    public static TimeLineChartFragment newInstance(String type, String marketId) {
        TimeLineChartFragment fragment = new TimeLineChartFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        bundle.putString("marketId", marketId);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static TimeLineChartFragment newInstance(String type, String marketId, boolean hideBottomCharts) {
        TimeLineChartFragment fragment = new TimeLineChartFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        bundle.putString("marketId", marketId);
        bundle.putBoolean("hideBottomCharts", hideBottomCharts);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (v != null) {
            if (isVisibleToUser) {
                setShowIndexChart();
            }
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            type = getArguments().getString("type");
            marketId = getArguments().getString("marketId");
            EnvironmentVariable.setProperty("k_line_market_id", marketId);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.open_planet_fragment_time_line, container, false);
        mTimeLineView = v.findViewById(R.id.timeline);
        progressBar = v.findViewById(R.id.progress_circular);
        mTimeLineView.setDateFormat("HH:mm");
//        int count = 241;
//        mTimeLineView.setCount(count, count, count);
        setShowIndexChart();
        initData("", true);
        return v;
    }

    @Override
    public void onResume() {
        super.onResume();
        marketId = EnvironmentVariable.getProperty("k_line_market_id");
        setShowIndexChart();
    }

    @Override
    public void onPause() {
        super.onPause();
        EnvironmentVariable.setProperty("k_line_market_id", marketId);
        if (getActivity().isFinishing()){
            MoveViewJob.getInstance(null, 0,0, null, null);

        }
    }

    public void showMa() {

        mTimeLineView.post(new Runnable() {
            @Override
            public void run() {
                mTimeLineView.showMa();
            }
        });
    }

    public void hideBottomCharts() {
        mTimeLineView.post(new Runnable() {
            @Override
            public void run() {
                mTimeLineView.hideBottomCharts();
            }
        });
    }

    public void showBoll() {

        mTimeLineView.post(new Runnable() {
            @Override
            public void run() {
                mTimeLineView.showBoll();
            }
        });
    }

    public void showMacd() {
        mTimeLineView.post(new Runnable() {
            @Override
            public void run() {
                mTimeLineView.showMacd();
            }
        });
    }

    public void showKdj() {
        mTimeLineView.post(new Runnable() {
            @Override
            public void run() {
                mTimeLineView.showKdj();
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onChartModeChangeEvent(ClickPositionEvent event) {
        //通过判断高度来确定点击的是哪一个图表
        mTimeLineView.switchChart(event.getE().getY());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoadMoreData(ChartLoadMoreEvent event) {
        if ("timeLine".equals(event.getType()) && !beforeTime.equals(event.getBeforeTime())) {
            beforeTime = event.getBeforeTime();
            initData(event.getBeforeTime(), false);
        }
    }

    public void reloadData() {
        initData("", false);
    }

    protected void initData(final String beforeTime, final boolean first) {
        if (progressBar != null) {
            progressBar.setVisibility(View.VISIBLE);
        }
        KLineUtil kLineUtil = new KLineUtil(getActivity());
        kLineUtil.getKLineModel(TAG, marketId, K_LINE_TYPE_MINUTE, String.valueOf(TimeUtils.getNowMills()),
                K_LINE_API_VERSION, beforeTime, new KLineUtil.OnGetHisDataListener() {
            @Override
            public void onGetHisDataSuccess(List<HisData> list) {
                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                }
                if ("".equals(beforeTime)) {
                    hisDataList.clear();
                }
                list.addAll(hisDataList);
                hisDataList = list;
                mTimeLineView.setLastClose(hisDataList.get(0).getClose());
                mTimeLineView.initData(hisDataList, first);
//                mTimeLineView.setLimitLine();
            }

            @Override
            public void onGetHisDataFail() {
                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                }
            }
        });

        /*new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                mTimeLineView.post(new Runnable() {
                    @Override
                    public void run() {
                        int index = (int) (Math.random() * 100);
                        HisData data = hisData.get(index);
                        HisData lastData = hisData.get(hisData.size() - 1);
                        HisData newData = new HisData();
                        newData.setVol(data.getVol());
                        newData.setClose(data.getClose());
                        newData.setHigh(Math.max(data.getHigh(), lastData.getClose()));
                        newData.setLow(Math.min(data.getLow(), lastData.getClose()));
                        newData.setOpen(lastData.getClose());
                        newData.setDate(System.currentTimeMillis());
                        hisData.add(newData);
                        mTimeLineView.addData(newData);
                    }
                });
            }
        }, 1000, 500);*/

       /* new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                mTimeLineView.post(new Runnable() {
                    @Override
                    public void run() {
                        mTimeLineView.refreshData((float) (hisData.get(0).getClose() + 10 * Math.random()));
                    }
                });
            }
        }, 1000, 1000);*/
    }

    /**
     * 设置显示哪个指标图
     */
    public void setShowIndexChart() {
        if (getArguments() != null && getArguments().getBoolean("hideBottomCharts")) {
            hideBottomCharts();
        }
        if ("MA".equals(CHART_MAIN_INDEX)) {
            showMa();
        } else {
            showBoll();
        }
        if ("MACD".equals(CHART_SUB_INDEX)) {
            showMacd();
        } else {
            showKdj();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

}
